package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.TradeUserSpuOrderBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.function.DimAsyncFunction;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2022/5/30 10:03
 */
public class Dws_09_DwsTradeUserSpuOrderWindow_Cache_Async extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_09_DwsTradeUserSpuOrderWindow_Cache_Async().init(3008, 2, "Dws_09_DwsTradeUserSpuOrderWindow_Cache_Async", Constant.TOPIC_DWD_TRADE_ORDER_DETAIL);
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        // 1. 去重: 按照订单详情id去重, 保留最后一条
        SingleOutputStreamOperator<JSONObject> distinctedStream = distinctByOrderDetailId(stream);
        
        // 2. 把数据封装到pojo中
        SingleOutputStreamOperator<TradeUserSpuOrderBean> beanStream = parseToBean(distinctedStream);
        
        // 3. 根据skuId去查找sku_info关联上spu_id和c3_id和tm_id信息. 其他维度信息等到聚合之后再去关联
        SingleOutputStreamOperator<TradeUserSpuOrderBean> beanStreamWithSpu = addSpuIdAndC3IdAndTmId(beanStream);
        
        // 4. 开窗聚合
        SingleOutputStreamOperator<TradeUserSpuOrderBean> aggregatedStream = windowAndAggregate(beanStreamWithSpu);
        
        // 5. 补充其他维度
        // spu -> tm -> c3->c2->c1
        SingleOutputStreamOperator<TradeUserSpuOrderBean> resultStream = addOtherDim(aggregatedStream);
        
        // 6. 写出到 clickhouse 中
        writeToClickhosue(resultStream);
    
    }
    
    private void writeToClickhosue(SingleOutputStreamOperator<TradeUserSpuOrderBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink(
            Constant.CLICKHOUSE_DB,
            "dws_trade_user_spu_order_window",
            TradeUserSpuOrderBean.class));
    }
    
    private SingleOutputStreamOperator<TradeUserSpuOrderBean> addOtherDim(SingleOutputStreamOperator<TradeUserSpuOrderBean> stream) {
        SingleOutputStreamOperator<TradeUserSpuOrderBean> streamWithSpu = AsyncDataStream.unorderedWait(
            stream,
            new DimAsyncFunction<TradeUserSpuOrderBean>() {
            
                @Override
                public void addDim(TradeUserSpuOrderBean input, JSONObject spuInfo) {
                    input.setSpuName(spuInfo.getString("SPU_NAME"));
                }
            
                @Override
                public String getTableName() {
                    return "dim_spu_info";
                }
            
                @Override
                public String getDimId(TradeUserSpuOrderBean input) {
                    return input.getSpuId();
                }
            },
            120,
            TimeUnit.SECONDS
        );
    
    
        SingleOutputStreamOperator<TradeUserSpuOrderBean> streamWithTm = AsyncDataStream.unorderedWait(
            streamWithSpu,
            new DimAsyncFunction<TradeUserSpuOrderBean>() {
            
                @Override
                public void addDim(TradeUserSpuOrderBean input, JSONObject dim) {
                    input.setTrademarkName(dim.getString("TM_NAME"));
                }
            
                @Override
                public String getTableName() {
                    return "dim_base_trademark";
                }
            
                @Override
                public String getDimId(TradeUserSpuOrderBean input) {
                    return input.getTrademarkId();
                }
            },
            120,
            TimeUnit.SECONDS
        );
    
    
        SingleOutputStreamOperator<TradeUserSpuOrderBean> streamWithC3 = AsyncDataStream.unorderedWait(
            streamWithTm,
            new DimAsyncFunction<TradeUserSpuOrderBean>() {
            
                @Override
                public void addDim(TradeUserSpuOrderBean input, JSONObject dim) {
                    input.setCategory3Name(dim.getString("NAME"));
                    input.setCategory2Id(dim.getString("CATEGORY2_ID"));
                }
            
                @Override
                public String getTableName() {
                    return "dim_base_category3";
                }
            
                @Override
                public String getDimId(TradeUserSpuOrderBean input) {
                    return input.getCategory3Id();
                }
            },
            120,
            TimeUnit.SECONDS
        );
    
    
        SingleOutputStreamOperator<TradeUserSpuOrderBean> streamWithC2 = AsyncDataStream.unorderedWait(
            streamWithC3,
            new DimAsyncFunction<TradeUserSpuOrderBean>() {
            
                @Override
                public void addDim(TradeUserSpuOrderBean input, JSONObject dim) {
                    input.setCategory2Name(dim.getString("NAME"));
                    input.setCategory1Id(dim.getString("CATEGORY1_ID"));
                }
            
                @Override
                public String getTableName() {
                    return "dim_base_category2";
                }
            
                @Override
                public String getDimId(TradeUserSpuOrderBean input) {
                    return input.getCategory2Id();
                }
            },
            120,
            TimeUnit.SECONDS
        );
    
        return AsyncDataStream.unorderedWait(
            streamWithC2,
            new DimAsyncFunction<TradeUserSpuOrderBean>() {
            
                @Override
                public void addDim(TradeUserSpuOrderBean input, JSONObject dim) {
                    input.setCategory1Name(dim.getString("NAME"));
                }
            
                @Override
                public String getTableName() {
                    return "dim_base_category1";
                }
            
                @Override
                public String getDimId(TradeUserSpuOrderBean input) {
                    return input.getCategory1Id();
                }
            },
            120,
            TimeUnit.SECONDS
        );
    }
    
    private SingleOutputStreamOperator<TradeUserSpuOrderBean> windowAndAggregate(SingleOutputStreamOperator<TradeUserSpuOrderBean> beanStreamWithSpu) {
      return  beanStreamWithSpu
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeUserSpuOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            )
            .keyBy(bean -> bean.getSpuId() + "_" + bean.getUserId())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeUserSpuOrderBean>() {
                    @Override
                    public TradeUserSpuOrderBean reduce(TradeUserSpuOrderBean b1,
                                                        TradeUserSpuOrderBean b2) throws Exception {
                        b1.setOrderAmount(b1.getOrderAmount() + b2.getOrderAmount());
                        b1.getOrderIdSet().addAll(b2.getOrderIdSet());
                        return b1;
                    }
                },
                new ProcessWindowFunction<TradeUserSpuOrderBean, TradeUserSpuOrderBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<TradeUserSpuOrderBean> elements,
                                        Collector<TradeUserSpuOrderBean> out) throws Exception {
    
                        String stt = AtguiguUtil.toDateTime(ctx.window().getStart());
                        String edt = AtguiguUtil.toDateTime(ctx.window().getEnd());
    
                        long ts = System.currentTimeMillis();
                        
    
    
                        TradeUserSpuOrderBean bean = elements.iterator().next();
                        bean.setStt(stt);
                        bean.setEdt(edt);
                        bean.setOrderCount((long) bean.getOrderIdSet().size());
    
                        bean.setTs(ts);
                        out.collect(bean);
    
    
                    }
                }
            );
    }
    
    
    private SingleOutputStreamOperator<TradeUserSpuOrderBean> addSpuIdAndC3IdAndTmId(
        SingleOutputStreamOperator<TradeUserSpuOrderBean> stream) {
        
        return AsyncDataStream.unorderedWait(
            stream,
            new DimAsyncFunction<TradeUserSpuOrderBean>() {
                @Override
                public void addDim(TradeUserSpuOrderBean input, JSONObject dim) {
                    input.setSpuId(dim.getString("SPU_ID"));// phoenix中所有字段大写
                    input.setCategory3Id(dim.getString("CATEGORY3_ID"));// phoenix中所有字段大写
                    input.setTrademarkId(dim.getString("TM_ID"));// phoenix中所有字段大写
                }
                
                @Override
                public String getTableName() {
                    return "dim_sku_info";
                }
                
                @Override
                public String getDimId(TradeUserSpuOrderBean input) {
                    return input.getSkuId();
                }
            },
            120,
            TimeUnit.SECONDS
        );
        
    }
    
    
    private SingleOutputStreamOperator<TradeUserSpuOrderBean> parseToBean(
        SingleOutputStreamOperator<JSONObject> stream) {
        return stream
            .map(new MapFunction<JSONObject, TradeUserSpuOrderBean>() {
                
                
                @Override
                public TradeUserSpuOrderBean map(JSONObject value) throws Exception {
                    
                    TradeUserSpuOrderBean bean = new TradeUserSpuOrderBean();
                    bean.setSkuId(value.getString("sku_id"));
                    bean.getOrderIdSet().add(value.getString("order_id"));
                    bean.setUserId(value.getString("user_id"));
                    bean.setTs(value.getLong("ts") * 1000);
                    
                    bean.setOrderAmount(value.getDouble("split_total_amount"));
                    
                    
                    return bean;
                }
            });
    }
    
    
    private SingleOutputStreamOperator<JSONObject> distinctByOrderDetailId(DataStreamSource<String> stream) {
        /*
        去重的优化:
            没有用到右边的数据, 所以只要第一条就可以了
            
         
         */
        return stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getString("id"))
            .process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {
                
                private ValueState<JSONObject> lastOrderDetailState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 状态中存储数据, 每新来一条数据,就比较时间, 新来的大于状态中的,更新状态中的数据
                    lastOrderDetailState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("lastOrderDetailState", JSONObject.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    JSONObject lastOrderDetail = lastOrderDetailState.value();
                    if (lastOrderDetail == null) {
                        lastOrderDetailState.update(obj);
                        out.collect(obj);
                    }
                }
            });
        
        
    }
    

}
/*
 多线程+多客户端
 
 线程池来执行线程
 
 
*/